import React, { Component } from 'react';
import { Stepper, Button, Toast, Modal } from 'antd-mobile';
import styled from 'styled-components'
import { TescoContair } from './shopcarStyleComp'
import Bscroll from 'better-scroll'
import { Link } from 'react-router-dom'
import cookie from 'react-cookies'

const alert = Modal.alert;

const Item = props => {
    return (
        <li className="shop_box">
            <h4> 聚美优品发货  </h4>
            <div className="shop_all">
                <div className="shop_check">
                    <label style={{ background: props.flag ? '#fe4070' : '#fff' }} onClick={() => { props.changeFlag(props.id) }}>√</label>
                </div>
                <div className="shop_img">
                    <img src={props.goodsimg}></img>
                </div>
                <div className="shop_details">
                    <h5> {props.goodstitle} </h5>
                    {props.numflag &&
                        <div className="specification">
                            <span>  </span>
                            <span> ×{props.num} </span>
                        </div> ||
                        <Stepper
                            className="stepperbox"
                            showNumber
                            max={10000}
                            min={1}
                            defaultValue={props.num}
                            onChange={(val) => { props.onChange(val, props.id) }}
                        />}
                    <div className="price">
                        <span className="price_one"> ￥{props.nowprice}</span>
                        {props.numflag && <span onClick={() => { props.RedactFlag(props.id) }}> 编辑 </span> ||
                            <span style={{ display: 'flex', alignItems: 'baseline' }}>
                                <Button
                                    onClick={() =>
                                        alert('Delete', '确定要删除此商品?', [
                                            { text: '取消', onPress: () => console.log('Cancel') },
                                            {
                                                text: '确定', onPress: () =>
                                                    props.remove(props.id)

                                            },
                                        ])
                                    }
                                > 删除</Button>
                                <span onClick={() => { props.RedactFlag(props.id) }}> 完成 </span>
                            </span>}
                    </div>
                </div>
            </div>
        </li>
    )
}

class Tesco extends Component {
    constructor(props) {
        super(props)
        this.state = {
            shopcar: localStorage.getItem('shopcar') && JSON.parse(localStorage.getItem('shopcar')) || [],
            val: 1,
            allCheck: false,
            totalPrice: 0,//总价
            numtrue: 0
        }
    }

    initVal = (val) => {
        this.setState({
            val: val
        })
    }

    RedactFlag = (id) => { //编辑和完成按钮
        this.allPrice()
        this.state.shopcar.map(item => {
            if (item.id == id) {
                item.numflag = !item.numflag
                return
            }
        })

        this.setState({
            shopcar: this.state.shopcar
        })
        localStorage.setItem('shopcar', JSON.stringify(this.state.shopcar))
    }

    onChange = (val, id) => {//更改步进器的函数
        // const ShopCar = localStorage.getItem('shopcar') && JSON.parse(localStorage.getItem('shopcar'))

        this.state.shopcar.map(item => {
            if (item.id == id) {
                item.num = val
                return
            }
        })

        this.setState({
            val: val,
            shopcar: this.state.shopcar
        })

        localStorage.setItem('shopcar', JSON.stringify(this.state.shopcar))
    }

    changeFlag = (id) => {//的单选按钮
        this.state.shopcar.map(item => {
            if (item.id == id) {
                item.flag = !item.flag
                return
            }
        })
        const f = this.state.shopcar.some(item => !item.flag)
        if (!f) {
            this.setState({
                allCheck: true
            })
        } else {
            this.setState({
                allCheck: false
            })
        }

        //更新界面
        this.setState({
            shopcar: this.state.shopcar
        })
        //同步本地存储
        localStorage.setItem('shopcar', JSON.stringify(this.state.shopcar))

        this.allPrice()
        this.numshop()

    }

    checkAllCheck = () => {
        const f = this.state.shopcar.some(item => !item.flag)

        if (!f) {
            this.setState({
                allCheck: true
            })
        } else {
            this.setState({
                allCheck: false
            })
        }
        this.numshop()
    }

    allChange = () => { //全选按钮
        //console.log(this.state.allCheck)
        if (!this.state.allCheck) {
            this.state.shopcar.map(item => {
                item.flag = true
                return
            })
        } else {
            this.state.shopcar.map(item => {
                item.flag = false
                return
            })
        }

        this.setState({
            allCheck: !this.state.allCheck
        })
        //同步本地存储
        localStorage.setItem('shopcar', JSON.stringify(this.state.shopcar))

        this.allPrice()
        this.numshop()
    }

    remove = (id) => { //删除按钮

        const data = JSON.parse(localStorage.getItem('shopcar'))
        const tureArr = []
        const Arr = [0]

        this.state.shopcar.map((item, index) => {
            if (item.id == id) {
                data.splice(index, 1)
                return
            }
            if (item.flag == true) {
                tureArr.push(item.flag)
                const price = item.num * item.nowprice
                Arr.push(Number(price.toFixed(2)))
                return
            }
        })

        this.setState({
            shopcar: data,
            numtrue: tureArr.length - 1,
            totalPrice: Arr.reduce(function (sum, value) {
                return sum + value
            })
        })
        localStorage.setItem('shopcar', JSON.stringify(data))


    }

    allPrice = () => {//总价
        const Arr = [0]

        this.state.shopcar.map(item => {
            if (item.flag === true) {
                const price = item.num * item.nowprice
                Arr.push(Number(price.toFixed(2)))
            }
            return
        })

        this.setState({
            totalPrice: Arr.reduce(function (sum, value) {
                return sum + value
            })
        })
    }

    goload = () => {//判断登录
        this.props.history.push('/shopcar')
        if (!cookie.load('username', { path: '/' })) {
            this.props.history.push('/mine/login')
        }
    }

    numshop = () => {//判断选中几个商品
        const tureArr = []
        this.state.shopcar.map(item => {
            if (item.flag == true) {
                tureArr.push(item.flag)
                return
            }
        })
        this.setState({
            numtrue: tureArr.length
        })

    }

    renderItem = () => {
        return this.state.shopcar && this.state.shopcar.map(item => <Item remove={this.remove} allPrice={this.allPrice} RedactFlag={this.RedactFlag} allChange={this.allChange} changeFlag={this.changeFlag} initVal={this.initVal} val={this.state.val} onChange={this.onChange} key={item.id}{...item} />)
    }

    render() {
        return (
            <TescoContair >
                {(this.state.shopcar && this.state.shopcar.length != 0) && <div className="shop_have_goods">
                    <div className="hello">商品数量有限，快去结算吧！</div>
                    <div className="shop_ul" ref={el => this.div = el} style={{ height: '5rem', overflow: 'hidden' }}>
                        <ul className="shop_jumei">
                            {this.renderItem()}
                        </ul>
                    </div>
                    <div className="shop_account">
                        <p className="all_check" onClick={this.allChange}>
                            <label style={{ background: this.state.allCheck && '#fe4070' || '#fff' }}>√</label>
                            <span>全选</span>
                        </p>
                        <p className="all_price">合计<span>￥{this.state.totalPrice}</span></p>
                        <Button className="go_account"
                            onClick={() =>
                                alert(' ', '还没有登录哦，快去登录吧！', [
                                    // { text: 'Cancel', onPress: () => console.log('cancel') },
                                    { text: 'OK', onPress: () => this.goload() },
                                ])
                            }>去结算({this.state.numtrue})</Button>
                    </div>
                </div> ||
                    <div className="shop_no_goods">
                        <div className="content">
                            <div className="oops">
                                <img src="https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1567138027252&di=0401aad2df62f9f9bf59d1dad995d6e3&imgtype=0&src=http%3A%2F%2F5b0988e595225.cdn.sohucs.com%2Fimages%2F20170910%2F1e1f40182a8146be9779d79a789feb0a.gif" alt="" />
                            </div>
                            <div className="empty_cart">您的购物车里面还没有商品，快去挑选心爱的商品吧！</div>
                            <div className="hang_out">
                                <Link to="/home/homemain/today">GoGoGo</Link>
                            </div>
                        </div>
                    </div>}
            </TescoContair>
        )
    }

    componentDidMount() {
        document.title="购物车"
        this.remove()
        this.checkAllCheck()
        this.allPrice()
        if (this.div) {
            new Bscroll(this.div, {
                click: true,
                mouseWheel:{
                    speed:20
                }
            })
        }

    }
}

export default Tesco